package data

import (
	"bufio"
	"fmt"
	"github.com/gogf/gf/errors/gerror"
	"gitlab.local/DO-module/new-filemanage-module/src/core/redisdb"
	"gitlab.local/DO-module/new-filemanage-module/src/service/user"
	"gorm.io/gorm"
	"io"
	"os"
	"strconv"
	"strings"
	"time"
)

const (
	SysShadow = "/etc/shadow"
)

type DataService struct {
	store *redisdb.RedisDb
}

func (Self *DataService) ParseFile(path string, handleFunc func(reader *bufio.Reader) error) error {
	f, err := os.Open(path)
	if err != nil {
		return gerror.Wrap(err, fmt.Sprintf("open %s faild", path))
	}
	defer f.Close()
	return handleFunc(bufio.NewReader(f))
}

// ExpireDays 帐号过期时间策略：
// 0 -> 不停用此帐号
// 1 -> 立即停用
// (>1) -> 按日期停用
// db 数据库连接，域用户必须传
func ExpireDays(name string, db *gorm.DB) (result int64) {
	if user.DomainUserExpireDays(name, db) == 1 {
		return 1
	}
	_ = (&DataService{}).ParseFile(SysShadow, func(reader *bufio.Reader) error {
		for {
			b, _, err := reader.ReadLine()
			if err == io.EOF {
				break
			}
			line := string(b)
			if !strings.HasPrefix(line, fmt.Sprintf("%s:", name)) {
				continue
			}
			fp := strings.Split(line, ":")
			expireString := strings.TrimSpace(fp[7])
			if expireString != "" {
				expire, err := strconv.ParseInt(expireString, 10, 64)
				if err != nil {
					break
				}
				result = expire
			}
			break
		}
		return nil
	})
	if result > 1 {
		result = CalculateExpire(result)
	}
	return
}

func CalculateExpire(day int64) int64 {
	addDay := time.Duration(day) * 24 * time.Hour
	lo := time.Date(1970, 01, 01, 0, 0, 0, 0, time.Local).Add(addDay)
	return lo.Unix()
}
